package models
import (
	"gintest/database"
	"time"
	"errors"
)
type PhoneCode struct{
	Id int `json:"id" gorm:"column:id;primary_key" form:"id"`
	Code string `json:"code" gorm:"column:code" form:"code"`
	Phone string `json:"phone" gorm:"column:phone" form:"phone"`
	
	Expire time.Time  `json:"expire" gorm:"column:expire;type:datetime" time_format:"2006-01-02 15:04:05" form:"expire"`
	CreateAt time.Time  `json:"create_at" gorm:"column:create_at;type:datetime" time_format:"2006-01-02 15:04:05" form:"create_at"`
	UpdateAt time.Time  `json:"update_at" gorm:"column:update_at;type:datetime" time_format:"2006-01-02 15:04:05" form:"update_at"`
}
func (PhoneCode) TableName() string {
	return "phone_code"
}
func CheckCode(code,phone string) error{
	var data PhoneCode
	database.SqlDB.Model(PhoneCode{}).Where("code=? and phone=?",code,phone).First(&data)
	
	if data.Id<=0{
		return errors.New("未找到验证码")
	}
	now := time.Now()
	if !now.Before(data.Expire){
		return errors.New("验证码已过期")
	}
	return nil
}
func AddPhoneCode(code,phone string) error{
	mm, _ := time.ParseDuration("5m")
	data:=&PhoneCode{
		Phone:phone,
		Code:code,
		Expire:time.Now().Add(mm),
		CreateAt:time.Now(),
		UpdateAt:time.Now(),
	}
	return database.SqlDB.Model(PhoneCode{}).Create(data).Error
}